package com.behealthy.android;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import com.behealthy.util.Utility;
import com.example.behealthy.R;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.BaseRequestListener;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.LoginButton;
import com.facebook.android.SessionEvents;
import com.facebook.android.SessionEvents.AuthListener;
import com.facebook.android.SessionEvents.LogoutListener;
import com.facebook.android.SessionStore;

public class BeHealthyDietProfileActivity extends Activity {
	
	//Facebook APP ID
			private static String App_ID = "264163113684409";
	
	// Instance of shared preferences
			String PREFS = "MyPrefs";
			private SharedPreferences sharedPrefs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_diet);
       
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        sharedPrefs = getSharedPreferences(PREFS, 0);
        
//		Create the Facebook Object using the app id.
    	Utility.mFacebook = new Facebook(App_ID);
//  Instantiate the AsyncRunner object for asynchronous API calls.
    	Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);
    	
    	  
//	    Restore facebook session if one exists
	    SessionStore.restore(Utility.mFacebook, this);
	    SessionEvents.addAuthListener(new FacebookAuthListener());
	    SessionEvents.addLogoutListener(new FacebookLogoutListener());
	    
	    Intent i = getIntent();
	    Boolean bool = i.getBooleanExtra("session", false);
       
        /**
         * Creating all buttons instances
         * */
         
        LoginButton btn_logout = (LoginButton) findViewById(R.id.btnFacebookLogout);
        TextView logout = (TextView) findViewById(R.id.link_to_logout);
        Button next = (Button) findViewById(R.id.btnNext);
        
        final Spinner diet = (Spinner) findViewById(R.id.diet_type);
         
        if(bool) {
        	btn_logout.setVisibility(View.VISIBLE);
        	btn_logout.init(this, Utility.mFacebook, true);
        	logout.setVisibility(View.GONE);
        }
        else {
        	btn_logout.setVisibility(View.GONE);
        	logout.setVisibility(View.VISIBLE);
        }
        
     // Listening to logout link
     			logout.setOnClickListener(new Button.OnClickListener() {
     				public void onClick(View v) {
     					// Switching to Register screen
     					Intent i = new Intent(getApplicationContext(),
     							BeHealthyLoginActivity.class);
     					startActivity(i);
     				}
     			});
     // Listening to next button
     			next.setOnClickListener(new Button.OnClickListener() {

					public void onClick(View v) {
						
						TextView tv = (TextView) diet.getSelectedView();
						String diet = tv.getText().toString();
						
						saveDetails(diet);
						
						Intent i = new Intent(getApplicationContext(),
								BeHealthyWorkoutProfileActivity.class);
						startActivity(i);
					}
     				
     			});
     			
     /**
      * Listening to the categories' links
      */
     			
     final AlertDialog.Builder builder = new AlertDialog.Builder(this);
     			
     // Vegetables
     			/*TextView vegetables = (TextView) findViewById(R.id.cat_vegetables);
     			vegetables.setOnTouchListener (new OnTouchListener() {
     				
     				public boolean onTouch(View v, MotionEvent event) {
     					
     					builder.setTitle(StringUtils.CAT_VEG);
     					builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
     						
     						public void onClick(DialogInterface dialog, int which, boolean isChecked) {
     							if(isChecked) {
     								checkedItems[which] = true;
     								itemsSelected[which] = items[which].toString().toLowerCase();
     							}
     							else { 
     								 checkedItems[which] = false;
     								 itemsSelected[which] = " ";
     							}
     							
     						}
     					});
     					builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
     						
     						public void onClick(DialogInterface dialog, int which) {
     							dialog.dismiss();
     							String str = "";
     							for(int i=0; i<itemsSelected.length; i++) {
     								if(!itemsSelected[i].endsWith(" ") ) str = str +itemsSelected[i]+",\n";
     							}
//     							categorieSelection.setMovementMethod(new ScrollingMovementMethod());
//     							categorieSelection.setText(str);
//     							categorieSelection.setVisibility(View.VISIBLE);
     							
     						}
     					});
     					builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
     						
     						public void onClick(DialogInterface dialog, int which) {
     							dialog.dismiss();
     							
     						}
     					});
     					AlertDialog alertDialog = builder.create();
     					alertDialog.show();
     					return false;
     				}
     			});*/
        
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_be_healthy_main, menu);
        return true;
    }
    
    public class FacebookAuthListener implements AuthListener {

        public void onAuthSucceed() {
            requestUserData();
        }

        public void onAuthFail(String error) {
//            mText.setText("Login Failed: " + error);
        }
    }
    
//	Callback for fetching current user's name, picture, id.
    
private class UserRequestListener extends BaseRequestListener {

    public void onComplete(final String response, final Object state) {
        JSONObject jsonObject;

        try {
            jsonObject = new JSONObject(response);
            Log.d("JSONResponse", response);
            final String name = jsonObject.getString("name");
            Utility.userUID = jsonObject.getString("id");
//            mUserEmail = jsonObject.getString("email");
            
            final String picURL = "http://graph.facebook.com/"+Utility.userUID+"/picture?type=small";
            Log.d("TAG", picURL);

//            mHandler.post(new Runnable() {
//                public void run() {
//                    mText.setText("Bine ai venit " + name + "!");
//                    mUserPic.setImageBitmap(Utility.getBitmap(picURL));
//                }
//            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
	}

//Request user name, and picture to show on the main screen.

private void requestUserData() {
//	mText.setText("Incarcare nume si poza de profil...");
	Bundle params = new Bundle();
	params.putString("fields", "name, picture, email");
	Utility.mAsyncRunner.request("me", params, new UserRequestListener());
}

public class FacebookLogoutListener implements LogoutListener {
    public void onLogoutBegin() {   
    }

    public void onLogoutFinish() {
    	Intent i = new Intent(getApplicationContext(), BeHealthyLoginActivity.class);
        startActivity(i);	
    }
}

private void logout (){
	Utility.mAsyncRunner.logout(getBaseContext(), new RequestListener() {
		  public void onComplete(String response, Object state) {
			  Intent i = new Intent(getApplicationContext(), BeHealthyLoginActivity.class);
              startActivity(i);
			  
		  }
		  
		  public void onIOException(IOException e, Object state) {}
		  
		  public void onFileNotFoundException(FileNotFoundException e,
		        Object state) {}
		  
		  public void onMalformedURLException(MalformedURLException e,
		        Object state) {}
		  
		  public void onFacebookError(FacebookError e, Object state) {}
		});
}

private void saveDetails(String diet) {
	
	Editor e = sharedPrefs.edit();
	
	if(diet.equalsIgnoreCase("normal")) diet = "N";
	else if(diet.equalsIgnoreCase("ovo-vegetarian")) diet = "OV";
	else if(diet.equalsIgnoreCase("lacto-vegetarian")) diet = "LV";
	else if(diet.equalsIgnoreCase("ovo-lacto-vegetarian")) diet = "OVL";
	e.putString("diet", diet);
	e.commit();
}
    
}
